/**
 * Notes: 企业微信API服务
 * Date: 2024-06-30
 */

const cloudBase = require('../../../framework/cloud/cloud_base.js');
const util = require('util');
const request = require('request');
const requestPromise = util.promisify(request);
const ConfigModel = require('../model/config_model.js');

// 企业微信API配置缓存
let tokenCache = {
    token: '',
    expireTime: 0
};

class WecomApi {
    /**
     * 获取企业微信访问token
     * @returns {Promise<string>} 访问token
     */
    static async getAccessToken() {
        // 检查缓存是否有效
        const now = new Date().getTime();
        if (tokenCache.token && tokenCache.expireTime > now) {
            return tokenCache.token;
        }
        
        // 获取企业微信配置
        const corpid = await this._getCorpId();
        const secret = await this._getCorpSecret();
        
        if (!corpid || !secret) {
            throw new Error('企业微信配置不完整');
        }
        
        // 请求企业微信API获取token
        const url = `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${corpid}&corpsecret=${secret}`;
        const response = await requestPromise({
            url,
            method: 'GET',
            json: true
        });
        
        if (response.body.errcode !== 0) {
            throw new Error(`获取企业微信token失败: ${response.body.errmsg}`);
        }
        
        // 更新缓存
        const token = response.body.access_token;
        const expiresIn = response.body.expires_in || 7200;
        tokenCache = {
            token,
            expireTime: now + (expiresIn - 300) * 1000 // 提前5分钟过期
        };
        
        return token;
    }
    
    /**
     * 获取企业微信用户详情
     * @param {string} userid 企业微信用户ID
     * @returns {Promise<object>} 用户详情
     */
    static async getUserDetail(userid) {
        try {
            // 获取访问token
            const token = await this.getAccessToken();
            
            // 请求企业微信API
            const url = `https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=${token}&userid=${userid}`;
            const response = await requestPromise({
                url,
                method: 'GET',
                json: true
            });
            
            if (response.body.errcode !== 0) {
                throw new Error(`获取用户信息失败: ${response.body.errmsg}`);
            }
            
            // 提取需要的字段
            const user = response.body;
            return {
                name: user.name,
                mobile: user.mobile,
                department: user.department ? user.department.join(',') : '',
                departmentId: user.department ? user.department[0] : '',
                position: user.position,
                email: user.email,
                avatar: user.avatar,
                title: user.position,
                isAdmin: user.is_leader_in_dept && user.is_leader_in_dept.some(v => v === 1)
            };
        } catch (error) {
            console.error('获取企业微信用户详情失败', error);
            // 返回一个基本的用户信息，避免整个流程中断
            return {
                name: '企业微信用户',
                mobile: '',
                department: '',
                departmentId: '',
                position: '',
                title: '',
                isAdmin: false
            };
        }
    }
    
    /**
     * 获取企业微信ID
     * @private
     */
    static async _getCorpId() {
        const config = await ConfigModel.getOne({
            where: {
                CONFIG_KEY: 'WECOM_CORPID'
            }
        });
        return config ? config.CONFIG_VALUE : '';
    }
    
    /**
     * 获取企业微信应用密钥
     * @private
     */
    static async _getCorpSecret() {
        const config = await ConfigModel.getOne({
            where: {
                CONFIG_KEY: 'WECOM_CORPSECRET'
            }
        });
        return config ? config.CONFIG_VALUE : '';
    }
}

module.exports = WecomApi; 